<?php
/**
 * @Author:      zk
 * @DateTime:    18-7-13 上午11:50
 * @Description: 用于维护角色的 控制器
 */
class OARoleController extends BaseController{

    public function __construct(){
        header('Access-Control-Allow-Origin:*');	//解决资源跨域问题
	header('Access-Control-Allow-Credentials', 'true');
    }
    
    /**
     * @Author:      zk
     * @DateTime:    18-7-13 下午2:57
     * @Description: 用于展示 角色的列表的
     * @param string $token         用户token
     * @param string $role_name     角色名称
     * @param int $page             页码 [默认 1]
     * @param int $page_size        每页显示数据条数 [默认 25]
     * @link: http://api.anhui.com/oa/role/index?token=1ce108359a4965e9305bd39b8692a1af&page=1&page_size=1&role_name=超级管理员
     */
    public function index(){
        $validator = Validator::make(Input::all(),
            array(
                'token' => 'required',
                'page' => 'integer',
                'page_size' => 'integer',
            )
        );
        $response = array('code' => 0, 'msg' => 'ok', 'result' => array());
        do {
            if ($validator->fails()) {
                $response = Lang::get('oa_error.args_error_100000');
                break;
            }
            $token = Input::get('token');
            $oa_user = $this->verificationOAUserToken($token, $response);
            if(is_null($oa_user)){                
                break;
            }
            $role_name  = Input::get('role_name', '');          //角色名称
            $page       = Input::get('page', 1);                //页码 [默认 1]
            $page_size  = Input::get('page_size', 25);          //每页显示数据条数 [默认 25]
            
            $select_arr = [
                'id', 'role_name', 'role_desc', 'status',
            ];
            $role_list = OARole::whereIn('status', [1, 2])
                    ->select($select_arr)
                    ->orderBy('id');
            if($role_name != ''){
                $role_list->where('role_name', 'like', '%'.$role_name.'%');
            }
            $count = $role_list->count();
            $role_list = $role_list->skip($page_size * ($page - 1))->take($page_size)->get()->toArray();
            
            $list = [];     //返回数组
            if(!empty($role_list)){
                foreach ($role_list as $k => $v) {
                    $temp = $v;
                    $user_list = OAUserRole::getUserByRoleid($v['id']);
                    $temp['user_num'] = count($user_list);
                    $temp['user_list'] = $user_list;
                    $list[] = $temp;
                }
            }
            
            $response = array('code' => 0, 'msg' => 'ok', 'result' => array('couont' => $count, 'list' => $list));
        } while (false);
        Log::info('info', ['system' => 'oa', 'event' => 'role/index', 'input' => Input::all(), 'output' => $response]);
        return json_encode($response);
    }
    
    /**
     * @Author:      zk
     * @DateTime:    18-7-24 下午3:13
     * @Description: 获取所有的角色列表以及该角色下的用户
     * @param string $token         用户token
     * @link: http://api.anhui.com/oa/role/indexAll?token=1ce108359a4965e9305bd39b8692a1af
     */
    public function indexAll(){
        $validator = Validator::make(Input::all(),
            array(
                'token' => 'required',
            )
        );
        $response = array('code' => 0, 'msg' => 'ok', 'result' => array());
        do {
            if ($validator->fails()) {
                $response = Lang::get('oa_error.args_error_100000');
                break;
            }
            $token = Input::get('token');
            $oa_user = $this->verificationOAUserToken($token, $response);
            if(is_null($oa_user)){                
                break;
            }
            
            $select_arr = [
                'id', 'role_name', 'role_desc', 'status',
            ];
            $role_list = OARole::where('status', 1)
                    ->select($select_arr)
                    ->orderBy('id')
                    ->get()
                    ->toArray();
            
            $list = [];     //返回数组
            if(!empty($role_list)){
                foreach ($role_list as $k => $v) {
                    $temp = $v;
                    $user_list = OAUserRole::getUserByRoleid($v['id']);
                    $temp['user_num'] = count($user_list);
                    $temp['user_list'] = $user_list;
                    $list[] = $temp;
                }
            }
            
            $response = array('code' => 0, 'msg' => 'ok', 'result' => array('list' => $list));
        } while (false);
        Log::info('info', ['system' => 'oa', 'event' => 'role/indexAll', 'input' => Input::all(), 'output' => $response]);
        return json_encode($response);
    }

    /**
     * @Author:      zk
     * @DateTime:    18-7-13 下午1:35
     * @Description: 添加/编辑 角色
     * @param string $token         用户token
     * @param string $role_name     角色名称
     * @param string $role_desc     角色描述
     * @param string $resources     为角色配置的资源 [多个资源以英文逗号分隔]
     * @param int $id               角色id
     * @link: http://api.anhui.com/oa/role/store?token=1ce108359a4965e9305bd39b8692a1af&role_name=超级管理员
     */
    public function store(){
        $validator = Validator::make(Input::all(),
            array(
                'token' => 'required',
                'role_name' => 'required',
            )
        );

        $response = array('code' => 0, 'msg' => 'ok');
        do{
            if ($validator->fails()) {
                $response = Lang::get('oa_error.args_error_100000');
                break;
            }
            $token = Input::get('token');
            $oa_user = $this->verificationOAUserToken($token, $response);
            if(is_null($oa_user)){                
                break;
            }
            $user_id    = $oa_user->id;                      //用户id
            $role_name  = Input::get('role_name');           //角色名称
            $role_desc  = Input::get('role_desc', '');       //角色描述
            $resources  = Input::get('resources', '');       //为角色配置的资源
            $id         = Input::get('id', '');              //角色id   
            
            //判断角色是否已经存在
            $exist_role = OARole::where('role_name', $role_name)
                    ->where('status', '!=', 3);
            if($id != ''){
                $exist_role->where('id', '!=', $id);
            }
            $exist_role = $exist_role->first();
            if($exist_role){
                $response = Lang::get('oa_error.role_exist_error_211001');
                break;
            }
            if($id != ''){
                $role = OARole::find($id);
                $op_old_data = json_encode($role);
                $role->updated_at = Common::num2DateTime(time());
                $role->updated_by = $user_id;
                $op_type = 2;
                $op_desc = '编辑角色';
            } else {
                $role = new OARole();
                $op_old_data = '';
                $role->status = 1;
                $role->created_at = Common::num2DateTime(time());
                $role->created_by = $user_id;
                $op_type = 1;
                $op_desc = '添加角色';
            }
            $role->role_name = $role_name;
            $op_new_data = json_encode($role);
            if($role_desc != ''){
                $role->role_desc = $role_desc;
            }
            
            try {
                $role->save();
            }catch (Exception $e){
                Log::info('info', ['system' => 'oa', 'event' => 'role/store', 'input' => Input::all(), 'exception' => $e]);
                $response = Lang::get('oa_error.role_create_error_211002');
                break;
            }
            $role_id = $role->id;   //角色id
            //赋予角色的权限资源    start
            OARoleResource::where('role_id', $role_id)->delete();   //删除该角色原有的 资源
            $resources_id = explode(',', rtrim($resources, ','));
            if(!empty($resources)){
                foreach ($resources_id as $val) {
                    //赋予角色资源
                    DB::table('oa_role_resource')->insertGetId(array(
                        'resource_id' => $val,
                        'role_id' => $role_id,
                        'created_at' => Common::num2DateTime(time()),
                        'updated_at' => Common::num2DateTime(time()),
                        'created_by' => $user_id,
                    ));
                }
            }

            OAOpLog::writeLog('role/store', $op_type, $op_desc, $op_old_data, $op_new_data, $user_id);
            //赋予角色的权限资源    end
            $response = array('code' => 0, 'msg' => 'ok');
        }while(false);
        Log::info('info', ['system' => 'oa', 'event' => 'role/store', 'input' => Input::all(), 'output' => $response]);
        return json_encode($response);
    }

    /**
     * @Author:      zk
     * @DateTime:    18-7-13 下午2:36
     * @Description: 修改角色的状态 [有用户在使用的角色时，不能冻结、删除该角色]
     * @param string $token         用户token
     * @param int $id               角色id
     * @param int $status           状态 (1:正常;2:冻结;3:删除;)
     * @link: http://api.anhui.com/oa/role/status?token=1ce108359a4965e9305bd39b8692a1af&id=1&status=1
     */
    public function status(){
        $validator = Validator::make(Input::all(),
            array(
                'token' => 'required',
                'id' => 'required',
                'status' => 'required',
            )
        );
        $response = array('code' => 0, 'msg' => 'ok');
        do{
            if ($validator->fails()) {
                $response = Lang::get('oa_error.args_error_100000');
                break;
            }
            $token = Input::get('token');
            $oa_user = $this->verificationOAUserToken($token, $response);
            if(is_null($oa_user)){                
                break;
            }
            $user_id    = $oa_user->id;                     //用户id
            $status     = Input::get('status');             //状态 (1:正常;2:冻结;3:删除;)
            $id         = Input::get('id');                 //角色id  
            
            $role_use = OAUserRole::where('status', 1)->where('role_id', $id)->first();
            if($role_use){
                $response = Lang::get('oa_error.role_use_error_211003');
                break;
            }
            $role = OARole::find($id);
            $op_old_data = json_encode($role);
            if(!$role){
                $response = Lang::get('oa_error.role_not_exist_error_211004');
                break;
            }

            $role->status = $status;
            $role->updated_at = Common::num2DateTime(time());
            $role->updated_by = $user_id;
            $statusDesc = [1 => '正常', 2 => '冻结', 3 => '删除'];
            $op_new_data = json_encode($role);
            try {
                $role->save();
            }catch (Exception $e){
                Log::info('info', ['system' => 'oa', 'event' => 'role/status', 'input' => Input::all(), 'exception' => $e]);
                $response = Lang::get('oa_error.role_update_status_error_211005');
                break;
            }

            try {
                OAOpLog::writeLog('role/status', 2, $statusDesc[$status], $op_old_data, $op_new_data, $user_id);
            } catch (Exception $e) {
                Log::info('info', ['system' => 'oa', 'event' => 'role/status', 'input' => Input::all(), 'exception' => $e]);
                $response = Lang::get('oa_error.approval_type_create_error_221002');
                break;
            }

            $response = array('code' => 0, 'msg' => 'ok');
        }while(false);
        Log::info('info', ['system' => 'oa', 'event' => 'role/status', 'input' => Input::all(), 'output' => $response]);
        return json_encode($response);
    }

    /**
     * @Author:      zk
     * @DateTime:    18-7-17 上午10:02
     * @Description: 获取角色详情
     * @param string $token         用户token
     * @param int $id               角色id
     * @link: http://api.anhui.com/oa/role/getRoleDetails?token=cbaeef3465cf329e7167fedb847fb11b&id=1
     */
    public function getRoleDetails(){
        $validator = Validator::make(Input::all(),
            array(
                'token' => 'required',
                'id' => 'required',
            )
        );
        $response = array('code' => 0, 'msg' => 'ok');
        do{
            if ($validator->fails()) {
                $response = Lang::get('oa_error.args_error_100000');
                break;
            }
            $token = Input::get('token');
            $oa_user = $this->verificationOAUserToken($token, $response);
            if(is_null($oa_user)){                
                break;
            }
            $id         = Input::get('id');                 //角色id
            $select_arr = [
                'id', 'role_name', 'role_desc', 'status',
            ];
            //角色详情
            $role_info = OARole::where('id', $id)->select($select_arr)->first();
            //该角色被赋予的权限资源
            $list = OARoleResource::where('role_id', $id)->select('resource_id')->get()->toArray();
            $role_res = [];
            if(!empty($list)){
                foreach ($list as $v) {
                    $role_res[] = $v['resource_id'];
                }
            }
            $role_menu = OAResource::getMenuByRoleId($id);  //获取角色下的目录资源
            
            $response = array('code' => 0, 'msg' => 'ok','result' => ['role_info' => $role_info, 'role_res' => $role_res, 'role_menu' => $role_menu]);
        }while(false);
        Log::info('info', ['system' => 'oa', 'event' => 'role/getRoleDetails', 'input' => Input::all(), 'output' => $response]);
        return json_encode($response);
    }

    /**
     * @Author:      zk
     * @DateTime:    18-7-18 下午2:35
     * @Description: 设置用户角色
     * @param string $token         用户token
     * @param int $role_id          角色id
     * @param int $type             用户id类型 [1:OA用户id;2:hrm平台用户id;]
     * @param string $user_ids      用户id [多个用户用英文逗号分隔]
     * @link: http://api.anhui.com/oa/role/setUserRole?token=74a833e1977d405573048b47fa33195b&role_id=1&user_ids=1,2&type=1
     */
    public function setUserRole() {
        $validator = Validator::make(Input::all(),
            array(
                'token' => 'required',
                'role_id' => 'required',
                'type' => 'required',
            )
        );

        $response = array('code' => 0, 'msg' => 'ok');
        do{
            if ($validator->fails()) {
                $response = Lang::get('oa_error.args_error_100000');
                break;
            }
            $token = Input::get('token');
            $oa_user = $this->verificationOAUserToken($token, $response);
            if(is_null($oa_user)){                
                break;
            }
            $user_id        = $oa_user->id;                         //管理员id
            $role_id        = Input::get('role_id');                //角色名称
            $type           = Input::get('type');                   //用户id类型 [1:OA用户id;2:hrm平台用户id;]
            $user_ids       = Input::get('user_ids', '');           //用户id [多个用户用英文逗号分隔]
            $user_id_arr    = explode(',', rtrim($user_ids, ','));  //用户id数组
            if($type == 2){
                $user_id_arr = OAUser::getUseridByHrmUserid($user_id_arr);
            }

            $op_old_data = OAUserRole::where('role_id', $role_id)->get()->toArray();
            if (empty($op_old_data)) {
                $isExit = TRUE;
            }
            DB::beginTransaction();
            try{
                $res = FALSE;
                $res_del = OAUserRole::where('role_id', $role_id)->delete();    //删除该角色的原有用户
                if (isset($isExit)) {
                    $res_del = $isExit;
                }
                if(!empty($user_id_arr)){
                    $insert_data = [];
                    foreach ($user_id_arr as $v) {
                        $temp = [
                            'user_id' => $v,
                            'role_id' => $role_id,
                            'status' => 1,
                            'created_by' => $user_id,
                            'created_at' => Common::num2DateTime(time()),
                        ];
                        $insert_data[] = $temp;
                    }
                    $res_ins = OAUserRole::insert($insert_data);
                    if($res_del && $res_ins){
                        $res = TRUE;
                    }
                }else{
                    if($res_del){
                        $res = TRUE;
                    }
                }
                if($res){
                    DB::commit();
                } else {
                    DB::rollback();
                    $response = Lang::get('oa_error.user_role_create_error_211010');
                    break;
                }
            } catch (\Exception $e){
                DB::rollback();
                Log::info('info', ['system' => 'oa', 'event' => 'role/setUserRole', 'input' => Input::all(), 'exception' => $e]);
                $response = Lang::get('oa_error.user_role_create_error_211010');
                break;
            }
            if (empty($user_ids)) {
                $op_type = 3;
                $op_desc = '清空角色下的用户';
            } else {
                $op_type = 2;
                $op_desc = '修改角色下的用户';
            }
            $op_new_data = OAUserRole::where('role_id', $role_id)->get()->toArray();
            if (empty($op_new_data)) {
                $op_new_data = '';
            } else {
                $op_new_data = json_encode($op_new_data);
            }
            if (empty($op_old_data)) {
                $op_old_data = '';
            } else {
                $op_old_data = json_encode($op_old_data);
            }
            try {
                OAOpLog::writeLog('role/setUserRole', $op_type, $op_desc, $op_old_data, $op_new_data, $user_id);
            } catch (Exception $e) {
                Log::info('info', ['system' => 'oa', 'event' => 'role/setUserRole', 'input' => Input::all(), 'exception' => $e]);
                $response = Lang::get('oa_error.approval_type_create_error_221002');
                break;
            }

        }while(false);
        Log::info('info', ['system' => 'oa', 'event' => 'role/setUserRole', 'input' => Input::all(), 'output' => $response]);
        return json_encode($response);
    }
    
    /**
     * @Author:      zk
     * @DateTime:    18-7-18 下午3:32
     * @Description: 获取OA用户列表     【 设置用户角色 】
     * @param string $token         用户token
     * @link: http://api.anhui.com/oa/role/getUserList?token=74a833e1977d405573048b47fa33195b
     */
    public function getUserList() {
        $validator = Validator::make(Input::all(),
            array(
                'token' => 'required',
            )
        );
        $response = array('code' => 0, 'msg' => 'ok');
        do{
            if ($validator->fails()) {
                $response = Lang::get('oa_error.args_error_100000');
                break;
            }
            $token = Input::get('token');
            $oa_user = $this->verificationOAUserToken($token, $response);
            if(is_null($oa_user)){                
                break;
            }
            $pid = 0;
            $list = HrmDepartment::getChildByParentid($pid);
            $response = array('code' => 0, 'msg' => 'ok','result' => $list);
        }while(false);
        Log::info('info', ['system' => 'oa', 'event' => 'role/setUserRole', 'input' => Input::all(), 'output' => $response]);
        return json_encode($response);
    }
    
    /**
     * @Author:      zk
     * @DateTime:    18-7-19 下午4:19
     * @Description: 获取OA用户列表 [按姓名查询]   【 设置用户角色 】
     * @param string $token         用户token
     * @param string $name          姓名
     * @link: http://api.anhui.com/oa/role/getUserListBySearch?token=74a833e1977d405573048b47fa33195b&name=ad
     */
    public function getUserListBySearch() {
        $validator = Validator::make(Input::all(),
            array(
                'token' => 'required',
            )
        );
        $response = array('code' => 0, 'msg' => 'ok');
        do{
            if ($validator->fails()) {
                $response = Lang::get('oa_error.args_error_100000');
                break;
            }
            $token = Input::get('token');
            $oa_user = $this->verificationOAUserToken($token, $response);
            if(is_null($oa_user)){                
                break;
            }
            $name = Input::get('name', '');     //姓名
            
            $hrm_uaer_id_arr = OAUser::getAllUserid(2);     //OA系统中用户对应的hrm用户id
            $list = HrmUser::getUserInfoByCondition($name, 1, $hrm_uaer_id_arr);
            $response = array('code' => 0, 'msg' => 'ok','result' => $list);
        }while(false);
        Log::info('info', ['system' => 'oa', 'event' => 'role/setUserRole', 'input' => Input::all(), 'output' => $response]);
        return json_encode($response);
    }

    

}